import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/useUserStore";
import { STORAGE_KEYS } from "@/config";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/auth/LoginView.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/register",
      name: "register",
      component: () => import("@/views/auth/RegisterView.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/",
      name: "home",
      component: () => import("@/views/home/HomeView.vue"),
      meta: { requiresAuth: true },
      redirect: "/chat",
      children: [
        {
          path: "chat",
          component: () => import("@/views/chat/ChatLayout.vue"),
          children: [
            {
              path: "",
              name: "chat",
              component: () => import("@/components/chat/Welcome.vue"),
            },
            {
              path: ":id",
              name: "chat-detail",
              component: () => import("@/components/chat/ChatContent.vue"),
            },
          ],
        },
        {
          path: "contacts",
          component: () => import("@/views/contacts/ContactsLayout.vue"),
          children: [
            {
              path: "",
              name: "contacts",
              component: () => import("@/components/contacts/Welcome.vue"),
            },
            {
              path: "new-friends",
              name: "new-friends",
              component: () => import("@/views/contacts/NewFriends.vue"),
            },
            {
              path: ":id",
              name: "contact-detail",
              component: () =>
                import("@/components/contacts/ContactDetail.vue"),
            },
          ],
        },
      ],
    },
    {
      path: "/:pathMatch(.*)*",
      name: "not-found",
      component: () => import("@/views/error/NotFoundView.vue"),
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const token = userStore.token;
  const requiresAuth = to.meta.requiresAuth;

  if (requiresAuth && !token) {
    // 需要登录但没有token，重定向到登录页
    next({ name: "login", query: { redirect: to.fullPath } });
  } else if (!requiresAuth && token) {
    // 已登录但访问登录/注册页，重定向到首页
    if (to.name === "login" || to.name === "register") {
      next({ name: "home" });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
